package com.qixin.web.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by Zhang on 2018/8/26.
 */
public class Sessioninterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HttpSession session = request.getSession();
        if (session.getAttribute("people_user") != null || session.getAttribute("pt_user") != null) {

            return true;
        } else {
            if (request.getRequestURI().equals("/qixin/weCollection/main.html")) {
                String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
                System.out.println("basPath="+basePath);
                session.setAttribute("preUrl",basePath+"/weCollection/main.html");
                redirect(request,response);
                return false;
            }
             /* if(request.getRequestURI().equals("/Zhang/motherNursing/editWord")){
                  return true;
              }*/
            System.err.println("来了:"+request.getRequestURI());
            redirect(request,response);
            return false;
        }
    }


    //对于请求是ajax请求重定向问题的处理方法
    public void redirect(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取当前请求的路径
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
        // 如果request.getHeader("X-Requested-With") 返回的是"XMLHttpRequest"说明就是ajax请求，需要特殊处理 否则直接重定向就可以了
        if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
            //告诉ajax我是重定向
            response.setHeader("REDIRECT", "REDIRECT");
            // 告诉ajax我重定向的路径
            response.setHeader("CONTENTPATH", basePath + "/weUser/login.html?url");
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        } else {
            response.sendRedirect(basePath + "/weUser/login.html");
        }

    }
}

